﻿var request = require('request');
var fs = require("fs");
var https = require('https');
var config = require('../config.js');
var log = require('./logger.js');
var db = require('../db/db.js');



var tools = {
    gettoken: function () {
        //获取token
        return new Promise((resolve, reject) => {
            var nalot = config.nalotonline;
            var str = "appId=" + nalot.appid + "&secret=" + nalot.secret;
            request({
                url: "https://" + nalot.host + ":" + nalot.port + "/iocm/app/sec/v1.1.0/login",
                headers: {
                    "content-type": "application/x-www-form-urlencoded"
                },
                rejectUnauthorized: false,
                method: "POST",
                body: str,
                agentOptions: {
                    pfx: fs.readFileSync(nalot.p12),
                    passphrase: nalot.password,
                }
            }, function (error, response, body) {
                //   console.log(error);
                //  console.log(response);
                //  console.log(body);
                if (!error && response.statusCode == 200) {
                    resolve(body);
                } else {
                    reject(error)
                }



            });

        })

    },
    //获取单个设备信息
    select_device_single: async function (deviceid, select = "imsi") {
        var tokenstr = await this.gettoken();
        var token = JSON.parse(tokenstr);
        //  console.log("token" + token.accessToken);
        return new Promise((resolve, reject) => {
            var nalot = config.nalotonline;

            var options = {
                url: "https://" + nalot.host + ":" + nalot.port + "/iocm/app/dm/v1.4.0/devices/" + deviceid + "?appId=" + nalot.appid + "&select=" + select,
                headers: {
                    "app_key": nalot.appid,
                    "Authorization": "Bearer " + token.accessToken,  //这里有一个空格注意了
                    "content-type": "application/json"
                },
                rejectUnauthorized: false,
                method: "GET",
                agentOptions: {
                    pfx: fs.readFileSync(nalot.p12),
                    passphrase: nalot.password,

                }
            };
            //  console.log(options);
            request(options, function (error, response, body) {
                // console.log('error:', error); // Print the error if one occurred
                // console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
                //  console.log('body:', body);
                if (!error && response.statusCode == 200) {
                    //res.write(body);
                    //res.end();

                    var result = {
                        "status": 200,
                        "message": "获取设备信息成功",
                        "data": body
                    }

                    resolve(result)
                } else {
                    var result = {
                        "status": 400,
                        "message": "获取设备信息失败",
                        "data": body
                    }

                    resolve(result)
                }



            });
        })

    },
    //注册设备
    regdevice: async function (verifyCode, nodeId, endUserId = "", psk = "", timeout = "") {
        var tokenstr = await this.gettoken();
        var token = JSON.parse(tokenstr);

        return new Promise((resolve, reject) => {
            var nalot = config.nalotonline;
            var data = {
                "nodeId": nodeId,
                "verifyCode": verifyCode


            }

            var options = {
                url: "https://" + nalot.host + ":" + nalot.port + "/iocm/app/reg/v1.2.0/devices?appId=" + nalot.appid,
                headers: {
                    "app_key": nalot.appid,
                    "Authorization": "Bearer " + token.accessToken,
                    "content-type": "application/json"
                },
                body: JSON.stringify(data),
                rejectUnauthorized: false,
                method: "POST",
                agentOptions: {
                    pfx: fs.readFileSync(nalot.p12),
                    passphrase: nalot.password,

                }
            };
            //  console.log(options);
            request(options, function (error, response, body) {
                //  console.log('error:', error); // Print the error if one occurred
                //  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
                //  console.log('body:', body);
                console.log("注册设备结果", body);
                log.info(body);

                if (!error && response.statusCode == 200) {
                    //res.write(body);
                    //res.end();

                    resolve(body)
                } else {
                    console.log(error);
                    reject(body)
                }



            });
        })

    },
    //protocolType 设备使用的协议类型，当前支持的协议类型：CoAP，huaweiM2M，Z-Wave，ONVIF，WPS，Hue，WiFi，J808，Gateway，ZigBee，LWM2M。
    //name设备名称,mid 厂商ID,m厂商名称,devmodel 设备型号，由厂商定义。,deviceType设备类型 大驼峰命名方式，例如：MultiSensor、ContactSensor、Camera和WaterMeter
    modifydevice: async function (deviceid, devicename, mid, m, devmodel, devicetype) {
        var tokenstr = await this.gettoken();
        var token = JSON.parse(tokenstr);
     //   console.log("token" + token.accessToken);
        return new Promise((resolve, reject) => {
            var nalot = config.nalotonline;
            var data = {
                "protocolType": "CoAP",
                "name": devicename,
                "manufacturerId": mid,
                "manufacturerName": m,
                "model": devmodel,
                "deviceType": devicetype


            }
            var options = {
                url: "https://" + nalot.host + ":" + nalot.port + "/iocm/app/dm/v1.2.0/devices/" + deviceid + "?appId=" + nalot.appid,
                headers: {
                    "app_key": nalot.appid,
                    "Authorization": "Bearer " + token.accessToken,
                    "content-type": "application/json"
                },
                body: JSON.stringify(data),
                rejectUnauthorized: false,
                method: "PUT",
                agentOptions: {
                    pfx: fs.readFileSync(nalot.p12),
                    passphrase: nalot.password,

                }
            };
            //console.log(options);
            request(options, function (error, response, body) {
                console.log('error:', error); // Print the error if one occurred
                console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
                console.log('body:', body);
                if (!error && response.statusCode == 204) {
                    //res.write(body);
                    //res.end();
                    // console.log("修改成功");
                    resolve(body)
                } else {
                    console.log(error);
                    resolve(error);
                }



            });
        })

    },
    //删除设备
    deldevice: async function (deviceid) {
        var tokenstr = await this.gettoken();
        var token = JSON.parse(tokenstr);
        //  console.log("token" + token.accessToken);
        return new Promise((resolve, reject) => {
            var nalot = config.nalotonline;

            var options = {
                url: "https://" + nalot.host + ":" + nalot.port + "/iocm/app/dm/v1.4.0/devices/" + deviceid + "?appId=" + nalot.appid,
                headers: {
                    "app_key": nalot.appid,
                    "Authorization": "Bearer " + token.accessToken,
                    "content-type": "application/json"
                },
                rejectUnauthorized: false,
                method: "DELETE",
                agentOptions: {
                    pfx: fs.readFileSync(nalot.p12),
                    passphrase: nalot.password,

                }
            };
            //   console.log(options);
            request(options, function (error, response, body) {

                console.info("删除设备" + body);
                if (!error && response.statusCode == 204) {
                    resolve(body)
                } else {
                    resolve(error);
                }



            });
        })

    },
    //下发命令
    devicecommands: async function (equipment_sn_id, tenant_sn_id, sn, deviceId, serviceId, method, outime, state, callbackUrl, orderid = "", tiyancode = "", place_sn_id = "0") {

        console.log("命令下发");
        var tokenstr = await this.gettoken();
        var token = JSON.parse(tokenstr);

        console.log(token);

        return new Promise((resolve, reject) => {
            var nalot = config.nalotonline;
            var data = {
                "deviceId": deviceId,
                "command": {
                    "serviceId": serviceId,
                    "method": method,
                    "paras": { "outime": outime, "state": state }



                },
                "callbackUrl": callbackUrl,
                expireTime: 0

            }
            console.log(JSON.stringify(data));
            var options = {
                url: "https://" + nalot.host + ":" + nalot.port + "/iocm/app/cmd/v1.4.0/deviceCommands?appId=" + nalot.appid,
                headers: {
                    "app_key": nalot.appid,
                    "Authorization": "Bearer " + token.accessToken,
                    "content-type": "application/json"
                },
                body: JSON.stringify(data),
                rejectUnauthorized: false,
                method: "POST",
                agentOptions: {
                    pfx: fs.readFileSync(nalot.p12),
                    passphrase: nalot.password,

                }
            };
            //console.log(options);
            request(options, function (error, response, body) {
                if (typeof (body) != "undefined") {

                    log.info("开机结果" + body);
                    var json = JSON.parse(body);
                    var commandId = "";
                    if (typeof (json.commandId) != "undefined") {
                        commandId = json.commandId;
                    }
                    db.asynquery("insert into crm_logs(deviceid,sn,createtime,title,content,code,equipment_sn_id,tenant_sn_id,state,commandid,tiyancode,place_sn_id) values(?,?,?,?,?,?,?,?,?,?,?,?)",
                        [deviceId, sn, new Date(), "设备运行", body, response.statusCode, equipment_sn_id, tenant_sn_id, 0, commandId, tiyancode, place_sn_id], function (err, result) {
                            console.log("插入日志", err, result);
                        });

                    if (typeof (json.error_code) != "undefined") {

                        console.log("设备出问题了!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");



                        db.asynquery("select * from crm_equipment where  id=?", [equipment_sn_id], async function (err, result) {
                            if (result.length > 0) {

                                var obj = result[0];
                                //if (obj.isjiangshi == 1) {
                                    console.log("obj", obj);
                                    var delresult = await tools.deldevice(obj.deviceId);
                                    var regdata = await tools.regdevice(obj.NBId, obj.NBId);
                                    regdata = JSON.parse(regdata);
                                    console.log("regdata",regdata);
                                    var updateresult = await db.execute("update crm_equipment set deviceId=?  where id=?", [regdata.deviceId, equipment_sn_id]);
                                    console.log("updateresult",updateresult);

                                    var deviceid = regdata.deviceId;
                                    var devicename = obj.equipment_sn;
                                    var mid = "SXMKSKJ01";
                                    var m = "SXMKSKJ";
                                    var devmodel = "REMCON01";
                                    var devicetype = "RemoteController";

                                    var modifydeviceobj = await tools.modifydevice(deviceid, devicename, mid, m, devmodel, devicetype);
                                    console.log("同步结果", modifydeviceobj);


                                    // db.asynquery("update crm_equipment set isjiangshi=? where id=?", [0, equipment_sn_id], function (err2, result2) {

                                    // });
                                //}

                            }
                        });


                        var result = {
                            "status": 501,
                            "message": "设备是僵尸",
                            "data": json
                        }
                        resolve(result);






                    } else {

                        db.asynquery("update crm_equipment set set_time=?,isjiangshi=? where id=?", [new Date(), 0, equipment_sn_id], function (err, result) {


                        });

                        if (orderid != "") {
                            db.asynquery("update crm_order set commandid=? where id=?", [json.commandId, orderid], function (err, result) {


                            });

                        }

                        if (!error && response.statusCode == 201) {
                            var result = {
                                "status": 200,
                                "message": "设备开启成功",
                                "data": body
                            }

                            resolve(result)
                        } else {
                            var result = {
                                "status": 400,
                                "message": "设备开启失败",
                                "data": body
                            }

                            resolve(result);
                        }
                    }

                }




            });
        })

    },
    subscriptionlist: async function () {
        var tokenstr = await this.gettoken();
        var token = JSON.parse(tokenstr);
        return new Promise((resolve, reject) => {
            var nalot = config.nalotonline;
            var options = {
                url: "https://" + nalot.host + ":" + nalot.port + "/iocm/app/sub/v1.2.0/subscriptions?appId=" + nalot.appid,
                headers: {
                    "app_key": nalot.appid,
                    "Authorization": "Bearer " + token.accessToken,  //这里有一个空格注意了
                    "content-type": "application/json"
                },
                rejectUnauthorized: false,
                method: "GET",
                agentOptions: {
                    pfx: fs.readFileSync(nalot.p12),
                    passphrase: nalot.password,

                }
            };
            //     console.log(options);
            request(options, function (error, response, body) {
                //  console.log('error:', error); // Print the error if one occurred
                // console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
                // console.log('body:', body);
                if (!error && response.statusCode == 200) {
                    //res.write(body);
                    //res.end();
                    resolve(body)
                } else {
                    reject(error)
                }



            });
        })

    },
    subadd: async function (notifyType, callbackUrl) {
        var tokenstr = await this.gettoken();
        var token = JSON.parse(tokenstr);
        return new Promise((resolve, reject) => {
            var nalot = config.nalotonline;
            var obj = {
                notifyType: notifyType,
                callbackUrl: callbackUrl
            }
            var options = {
                url: "https://" + nalot.host + ":" + nalot.port + "/iocm/app/sub/v1.2.0/subscriptions",
                headers: {
                    "app_key": nalot.appid,
                    "Authorization": "Bearer " + token.accessToken,  //这里有一个空格注意了
                    "content-type": "application/json"
                },
                body: JSON.stringify(obj),
                rejectUnauthorized: false,
                method: "POST",
                agentOptions: {
                    pfx: fs.readFileSync(nalot.p12),
                    passphrase: nalot.password,

                }
            };
            //console.log(options);
            request(options, function (error, response, body) {
                // console.log('error:', error); // Print the error if one occurred
                //console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
                //console.log('body:', body);
                if (!error && response.statusCode == 200) {
                    //res.write(body);
                    //res.end();
                    resolve(body)
                } else {
                    reject(error)
                }



            });
        }).catch(error => { console.log('caught', error); })

    },
    subdel: async function (subscriptionId) {
        var tokenstr = await this.gettoken();
        var token = JSON.parse(tokenstr);
        return new Promise((resolve, reject) => {
            var nalot = config.nalotonline;
            var options = {
                url: "https://" + nalot.host + ":" + nalot.port + "/iocm/app/sub/v1.2.0/subscriptions/" + subscriptionId,
                headers: {
                    "app_key": nalot.appid,
                    "Authorization": "Bearer " + token.accessToken,  //这里有一个空格注意了
                    "content-type": "application/json"
                },
                rejectUnauthorized: false,
                method: "DELETE",
                agentOptions: {
                    pfx: fs.readFileSync(nalot.p12),
                    passphrase: nalot.password,

                }
            };


            //console.log(options);
            request(options, function (error, response, body) {
                //   console.log('error:', error); // Print the error if one occurred
                // console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
                //  console.log('body:', body);
                if (!error && response.statusCode == 200) {
                    //res.write(body);
                    //res.end();
                    resolve(body)
                } else {
                    reject(error)
                }



            });
        }).catch(error => { console.log('caught', error); })

    },

}


module.exports = tools;